package com.hh85.updateapk;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import java.io.File;

public class UpdateApk {
    private AlertDialog dialog;
    private ProgressBar progressBar;
    private Activity context;
    private String TAG = "UpdateApk";
     public UpdateApk(Activity context){
        this.context = context;
        progressBar = new ProgressBar(context,null,android.R.attr.progressBarStyleHorizontal);

        progressBar.setMax(100);
        progressBar.setProgress(0);

    }


    /**
     *
     * @param downUrl 安装包地址
     * @param title  提示标题
     * @param msg  提示内容
     */
    public  void show(final String downUrl,String title,String msg){
        int i = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(i == PackageManager.PERMISSION_GRANTED){
            dialog = new AlertDialog.Builder(context)
                    .setTitle(title)
                    .setMessage(msg)
                    .setPositiveButton("立即更新",null)
                    .setView(progressBar)
                    .setCancelable(false)
                    // .setNegativeButton("关闭",null)
                    .show();
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    view.setEnabled(false);
                    downloadFile(downUrl);
                }
            });


        }else{
            //权限不足
            Toast.makeText(context,"权限不足",Toast.LENGTH_SHORT).show();
            return;
        }
    }

    /**
     *
     * @param downUrl
     */
    public  void show(final String downUrl){
        int i = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(i == PackageManager.PERMISSION_GRANTED){
            dialog = new AlertDialog.Builder(context)
                    .setTitle("有新版本,需要更新")
                    .setMessage("修复了一些BUG")
                    .setPositiveButton("立即更新",null)
                    .setView(progressBar)
                    .setCancelable(false)
                    // .setNegativeButton("关闭",null)
                    .show();
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    view.setEnabled(false);
                    downloadFile(downUrl);
                }
            });


        }else{
           //权限不足
          Toast.makeText(context,"权限不足",Toast.LENGTH_SHORT).show();
            return;
        }
    }

    private void downloadFile(String url){
        // url服务器地址，saveurl是下载路径，fileName表示的是文件名字
        final String saveurl="/app/";
        final String fileName = System.currentTimeMillis()+".apk";

        DownloadUtil.get().download(context, url,saveurl,fileName,  new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
                        // 这里的弹框设置了进度条，下同
                        dialog.dismiss();

                        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            return;
                        }

                        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/download"+saveurl+fileName);

                        try {

                            OpenFileUtils.install(context,file);
                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onDownloading(int progress) {
                //  dialog.setProgress(progress);
                progressBar.setProgress(progress);
            }

            @Override
            public void onDownloadFailed() {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();

                    }
                });
            }
        });
    }


}
